var websock = null
var _globalcallback = null
// 初始化weosocket
function initWebSocket () {
  // ws地址
  var wsuri = 'ws://127.0.0.1:7081'
  websock = new WebSocket(wsuri)
  websock.onmessage = function (e) {
    websocketonmessage(e)
  }
  websock.onclose = function (e) {
    websocketclose(e)
  }
  websock.onopen = function () {
    websocketOpen()
  }
  // 连接发生错误的回调方法
  websock.onerror = function () {
    var websocketmsg = 'WebSocket连接发生错误'
    localStorage.setItem('websocketmsg', websocketmsg)
  }
}

// 实际调用的方法
function sendSock (agentData, callback) {
  if (callback) {
    _globalcallback = callback
  } // 回调
  if (websock.readyState === websock.OPEN) {
    // 若是ws开启状态
    websocketsend(agentData)
  } else if (websock.readyState === websock.CONNECTING) {
    // 若是 正在开启状态，则等待1s后重新调用
    setTimeout(function () {
      sendSock(agentData, callback)
    }, 1000)
  } else {
    // 若未开启 ，则等待1s后重新调用
    setTimeout(function () {
      sendSock(agentData, callback)
    }, 1000)
  }
}

// 数据接收
function websocketonmessage (e) {
  _globalcallback(JSON.parse(e.data))
}

// 数据发送
function websocketsend (agentData) {
  console.log('agentData', agentData)
  websock.send(JSON.stringify(agentData))
}

// 关闭
function websocketclose (e) {
  console.log('connection closed')
}

function websocketOpen (e) {
  console.log('连接成功')
  var websocketmsg = '连接成功'
  localStorage.setItem('websocketmsg', websocketmsg)
}

initWebSocket()
export {
  sendSock
}
